import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
//@GetMapping(value = "project/extend.js")
public class ExtendJsServlet extends HttpServlet {

	private String jsFiles = ParameConfig.jsFiles;

	private static final long serialVersionUID = 3835272136202455840L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		resp.setHeader("Cache-Control", "no-cache");
//		resp.setHeader("Pragma", "no-cache");
//		resp.setDateHeader("Expires", 0);
		resp.setContentType("text/javascript;charset=UTF-8");
		PrintWriter out = resp.getWriter();
		String js = mergeJs();
		out.println(js);
		out.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
	private String mergeJs() throws IOException {
		if (StringUtils.isBlank(jsFiles)) {
			return "";
		}
		String jsPath = ParameConfig.jsLocation;
		if (!jsPath.startsWith("/")) {
			jsPath = "/" + jsPath;
		}
		if (!jsPath.endsWith("/")) {
			jsPath = jsPath + "/";
		}
		String[] files = StringUtils.split(jsFiles, ",");
		StringBuffer result = new StringBuffer();
		for (int i = 0; i < files.length; i++) {
			String file = StringUtils.trimToEmpty(files[i]);
			String resourcePath = jsPath + file;
			ServletContext context = getServletContext();
			InputStream resource = context.getResourceAsStream(resourcePath);
			if (null == resource) {
				throw new IOException("资源文件 'classpath:" + resourcePath + "' 不存在");
			}
			String content = IOUtils.toString(resource, "UTF-8");
			if (null == content) {
				content = "";
			}
			content = "/**"
					+"\n From "+file
					+"\n */" + "\n" + content;
			result.append(content).append("\n");
		}
		return result.toString();
	}	
}
